package com.feishi.core.media.opencv.util;

import com.feishi.core.util.common.LibraryUtil;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.test.imgcodecs.ImgcodecsTest;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @version 1.0
 * @auth caixq
 * @time 18-4-20 11:32
 **/
public class OpenCvUtil {

    public static void loadLibrary(){
        LibraryUtil.load("lib"+ Core.NATIVE_LIBRARY_NAME+".so");
    }
    public static BufferedImage MatToBufImg(Mat mat, String fileExtension){
        MatOfByte mob = new MatOfByte();
        Imgcodecs.imencode(fileExtension,mat,mob);
        byte[] byteArray = mob.toArray();
        BufferedImage bufImage = null;
        try {
            InputStream in = new ByteArrayInputStream(byteArray);
            bufImage = ImageIO.read(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bufImage;
    }
    public static ByteArrayInputStream MatToStream(Mat mat, String fileExtension){
        MatOfByte mob = new MatOfByte();
        Imgcodecs.imencode(fileExtension,mat,mob);
        return new ByteArrayInputStream(mob.toArray());
    }
    public static byte[] MatToBytes(Mat mat, String fileExtension){
//        byte [] grayData = new byte[mat.cols()*mat.rows()];
//        mat.get(0,0,grayData);
        MatOfByte mob = new MatOfByte();
        Imgcodecs.imencode(fileExtension,mat,mob);
        
        return mob.toArray();
    }
    public static byte[] MatToBytes(Mat mat){
        byte [] grayData = new byte[mat.cols()*mat.rows()];
        mat.get(0,0,grayData);
        return grayData;
    }
    public static Mat bufImgToMat(BufferedImage bufferedImage){

        int itype = BufferedImage.TYPE_3BYTE_BGR;
        int mtype = CvType.CV_8UC3;
        if (bufferedImage.getType() != itype) {

            // Create a buffered image
            BufferedImage image = new BufferedImage(bufferedImage.getWidth(),
                    bufferedImage.getHeight(), itype);

            // Draw the image onto the new buffer
            Graphics2D g = image.createGraphics();
            try {
                g.setComposite(AlphaComposite.Src);
                g.drawImage(bufferedImage, 0, 0, null);
            } finally {
                g.dispose();
            }
        }

        byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
        Mat mat = Mat.eye(bufferedImage.getHeight(), bufferedImage.getWidth(), mtype);
        mat.put(0, 0, pixels);
        return mat;
    }
    /**
     * 未经测试,无法确定效果
     * */
    public static Mat bytesToMat(byte[] pixels){
        Mat mat =new Mat();
        mat.put(0, 0, pixels);
        return mat;
    }
}
